﻿using System;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Web;
using System.Xml;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Rookey.Frame.IMCore.IO;
using System.Threading;
using Rookey.Frame.IMCore;

/// <summary>
///DownloadHandler 的摘要说明
/// </summary>
namespace Rookey.Frame.IMWeb
{
	public class DownloadJsHandler : IHttpHandler
	{
		static string EmbedJsFormat =
        "var IMCore = {{}};\r\n" +
		"IMCore.Config = {{\r\n" +
		"	Version: \"{0}\",\r\n" +
        "	ServiceUrl: \"{1}\",\r\n" +
        "	ResPath: \"{3}\"\r\n" +
		"}};\r\n" +
		"\r\n" +
		"document.write('<link href=\"{2}/Themes/Default/Desktop/Desktop.css\" rel=\"stylesheet\" type=\"text/css\" />');\r\n" +
		"document.write('<script src=\"{2}/Core/Common.js\" type=\"text/javascript\"></script>');\r\n" +
		"document.write('<script src=\"{2}/Core/Extent.js\" type=\"text/javascript\"></script>');\r\n" +
		"document.write('<script src=\"{2}/Core/Main.js\" type=\"text/javascript\"></script>');\r\n" +
		"document.write('<script src=\"{2}/Core/Main/Desktop.js\" type=\"text/javascript\"></script>');\r\n" +
		"document.write('<script src=\"{2}/Core/Main/Window.js\" type=\"text/javascript\"></script>');\r\n";

		void IHttpHandler.ProcessRequest(HttpContext context)
		{
			string fileName = System.IO.Path.GetFileName(context.Request.FilePath).ToLower();
			if (fileName == "config.js.aspx")
			{
				String js = String.Format(
                    @"
					IMCore.Config = {{
						Version: '{0}',
						ServiceUrl: '{1}',
						ResPath: '{2}'
					}};",
					ServerImpl.Instance.Version,
                    ServerImpl.Instance.ServiceUrl,
                    ServerImpl.Instance.ResPath
				);

				context.Response.ContentType = "application/x-javascript";
				context.Response.Write(js);
			}
			else if (fileName == "embed.js.aspx")
			{
				var resRoot = ServerImpl.Instance.ServiceUrl;
				if (!resRoot.EndsWith("/")) resRoot += "/";
				resRoot += ServerImpl.Instance.ResPath;
                string js = String.Format(EmbedJsFormat, ServerImpl.Instance.Version, ServerImpl.Instance.ServiceUrl, resRoot, ServerImpl.Instance.ResPath);

				context.Response.ContentType = "application/x-javascript";
				context.Response.Write(js);
			}
		}

		bool IHttpHandler.IsReusable
		{
			get { return true; }
		}
	}
}